import React from "react";
import { routerRedux } from 'dva/router';
import {
  Form,
  BackTop,
  Divider,
  Layout,
  Modal,
  Input,
  Col,
  Row,
  notification,
  message
} from "antd";
import {
  FileUnknownOutlined,
  CommentOutlined,
  UpOutlined,
  SmileOutlined
} from "@ant-design/icons";
import { connect } from "dva";
// import router from 'umi/router';
import SiderMenu from "@/components/SiderMenu";
import { getFlatMenuKeys } from "@/components/SiderMenu/SiderMenuUtils";
import memoizeOne from "memoize-one";
import isEqual from "lodash/isEqual";
import styles from "./BasicLayout.less";
import router from "umi/router";
import * as requesturl from "@/services/request-url";


const { Header, Content, Footer } = Layout;
const { TextArea } = Input;

function getMenuItem(route) {
  if (route.name) {
    const menuItem = {
      name: route.name,
      path: route.path,
      icon: route.icon,
      hideInMenu: route.hideInMenu ? route.hideInMenu : false
    };
    if (
      Array.isArray(route.routes) &&
      route.routes.length > 0 &&
      !route.hideChildrenInMenu
    ) {
      const children = [];
      route.routes.forEach(item => {
        const child = getMenuItem(item);
        if (child) {
          children.push(child);
        }
      });
      if (children.length > 0) {
        menuItem.children = children;
      }
    }
    return menuItem;
  }
  return null;
}

function getMenu(routes) {
  const menu = [];
  routes.forEach(route => {
    const menuItem = getMenuItem(route);
    if (menuItem) {
      menu.push(menuItem);
    }
  });
  return menu;
}

const memoizeOneGetMenu = memoizeOne(getMenu, isEqual);

@connect(({ global }) => ({ userId: global.userId }))
class BasicLayout extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      textareaValue: "",
      value: 0,
      inputValue: "",
      headerInformationNum: 0,
      username: ""
    };
  }
  getCookie(name) {
    let arr;
    const regx = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(regx))
      return (unescape(arr[2]));
    else
      return null;
  }
  //tokenn
  async getToken() {
    Object.defineProperty(navigator, 'userAgent', {
      value: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36',
      writable: false
    });
    console.log(navigator.userAgent);
    
    let token = undefined;
    const casTokenUrl = `${requesturl.login}/cas/jwt/token.do`;
    await fetch(casTokenUrl, {
      method: 'POST',
      credentials: 'include',
    }).then(res =>
      res.json().then(data => {
        // console.log(111111111111)
        // console.log(data)
        const { returnStatus, returnInfo } = data
        if (returnStatus == 200) {
          const currentTime = new Date().getTime();
          window.tokenLastUpdateTime = currentTime;
          window.epmToken = returnInfo;
          token = returnInfo;
          sessionStorage.setItem("token", token)
          this.getUserInfo()
        }
        // else if (returnStatus == 401) {
        // window.location = `http://172.16.193.25:9009` + returnInfo;
        // let a = document.createElement("a")
        // a.href = `${requesturl.login}/cas/jwt/login.do`;
        // a.click();
        // }
      })
    );
  }
  componentDidMount = () => {
    //页面初始化拿token
    this.getToken()
    this.getHeaderInformationNum()
  }

  //拿user信息
  getUserInfo = () => {
    this.props
      .dispatch({
        type: "global/getUserInfo",
        payload: {}
      })
      .then(res => {
        console.log(res);
        if (res) {
          this.setState({
            username: res.data.userName
          })
          sessionStorage.setItem("userId", res.data.userId)
        }
      });
  }
  //获取访问人数
  getHeaderInformationNum = () => {
    this.props
      .dispatch({
        type: "global/headerInformationNum",
        payload: {}
      })
      .then(res => {
        if (res) {
          this.setState({
            headerInformationNum: res.data
          });
        }
      });
  }

  handleTextareaChange = e => {
    this.setState({
      textareaValue: e.target.value
    });
  };
  handleInputChange = e => {
    this.setState({
      inputValue: e.target.value
    });
  };
  showModal = () => {
    this.setState({
      visible: true,
      inputValue: "",
      textareaValue: ""
    });
  };
  //取消
  cancelHideModal = () => {
    this.setState({
      visible: false,
      inputValue: "",
      textareaValue: ""
    });
  };
  //提交
  hideModal = () => {
    this.setState({
      visible: false,
      inputValue: "",
      textareaValue: ""
    });
    this.props
      .dispatch({
        type: "global/insert",
        payload: {
          opinionInfo: this.state.textareaValue,
          title: this.state.inputValue
        }
      })
      .then(res => {
        // this.opinionInfo = this.state.textareaValue;
        // this.title = this.state.inputValue;
        console.log(this.opinionInfo);
        console.log(this.title);
        console.log(res);
      });
    notification.open({
      message: "意见提交成功",
      icon: <SmileOutlined style={{ color: "#108ee9" }} />
    });
  };

  handleRouterPage = () => {
    router.push({
      pathname: "/helpdoc"
    });
  };
  //表单单选按钮
  onChangeRadio = e => {
    console.log("e.target", e.target);
  };
  render() {
    const {
      route: { routes },
      children,
      value
    } = this.props;
    const { headerInformationNum, username, visible } = this.state;
    const menuData = memoizeOneGetMenu(routes);
    const flatMenuKeys = getFlatMenuKeys(menuData);
    const onChange = e => {
      console.log("Change:", e.target.value);
    };
    return (
      <Layout className={styles.layout}>
        <Header className={styles.layoutHeader}>
          <SiderMenu
            onCollapse="0"
            menuData={menuData}
            flatMenuKeys={flatMenuKeys}
            headerInformationNum={headerInformationNum}
            username={username}
            {...this.props}
          />
        </Header>
        <Content className={styles.layoutContent}>
          <div className={styles.layoutContentBox}>{children}</div>
          <div className={styles.footerBox}>
            {/* <div style={{margin:"20px"}}> */}
            <div
              className={styles.overallBox}
              onClick={() => this.handleRouterPage()}
              style={{ cursor: "pointer" }}
            >
              <FileUnknownOutlined
                title="帮助文档"
                className={styles.backTopIcon}
              />
              <div className={styles.titleShow}>帮助文档</div>
            </div>

            <div className={styles.overallBox} onClick={this.showModal}>
              <CommentOutlined
                className={styles.backTopIcon}
                title="意见反馈"
              />
              <div onClick={this.showModal} className={styles.titleShow}>
                意见反馈
              </div>
            </div>
            {visible ? (
              <Modal
                title="意见反馈"
                visible={visible}
                onOk={this.hideModal}
                onCancel={this.cancelHideModal}
                okText="提交"
                cancelText="取消"
                centered
              // style={{ textAlign: "center" }}
              >
                <Form>
                  <Form.Item label="意见标题" name="意见标题">
                    <Input
                      placeholder="请输入标题(最多20个字符)"
                      value={this.state.inputValue}
                      maxLength={20}
                      style={{
                        width: "100%",
                        resize: "none",
                        color: "black"
                      }}
                      onChange={this.handleInputChange}
                    />
                  </Form.Item>
                  <Form.Item label="意见内容" name="意见内容">
                    <TextArea
                      value={this.state.textareaValue}
                      placeholder="请输入您要反馈的意见(最多200个字符)"
                      allowClear
                      maxLength={200}
                      style={{
                        width: "100%",
                        resize: "none",
                        color: "black"
                      }}
                      onChange={this.handleTextareaChange}
                      rows={5}
                      showCount={"true"}
                    />
                  </Form.Item>
                </Form>
              </Modal>
            ) : null}
          </div>
          <BackTop
            className={styles.backTop}
            visibilityHeight={0}
            style={{ height: "150px", right: "4%" }}
          >
            <div className={styles.overallBox}>
              <UpOutlined className={styles.backTopIcon} title="返回顶部" />
              <div className={styles.titleShow}>返回顶部</div>
            </div>
            {/* </div> */}
          </BackTop>
        </Content>
        <Footer className={styles.layoutFooter}>
          <div className={styles.layoutFooterLink}>
            <span>
              <Row justify="center" >
                {/* <Col span={1}>友情链接</Col>
                <Divider type="vertical" />| */}
                <Col span={3}>
                  <a href="https://www.bonc.com.cn/big-data-plat">大数据治理平台</a>|
                </Col>
                <Col span={3}>
                  <a href="https://www.bonc.com.cn/data-science-cloud">数据科学云</a>|
                </Col>
                <Col span={3}>
                  <a href="https://www.bonc.com.cn/bonc-ht">大数据可视化</a>|
                </Col>
                <Col span={3}>
                  <a href="https://www.bonc.com.cn/ai-on-cloud">人工智能云平台</a>
                </Col>
              </Row>
              {/* <iframe id="iframe" src="http://172.16.193.25:9009/portal/pageView?pageId=index"></iframe> */}
            </span>
            <div className={styles.layoutFooterBottom}>
              <span>大数据共享服务管理系统@2021 | 东方国信研发团队&nbsp;</span>
            </div>
          </div>
        </Footer>
      </Layout>
    );
  }
}

export default BasicLayout;
